<?php

namespace frontend\modules\yii\controllers;

use frontend\modules\yii\models\FrameCatalogue;
use frontend\modules\yii\models\FrameDir;
use yii\base\Model;
use yii\web\Controller;
use frontend\modules\yii\models\FrameNavs;
use frontend\modules\yii\models\FrameArticles;
use yii\web\UploadedFile;

/**
 * Default controller for the `yii` module
 */
class ManagerController extends Controller
{
    public $layout = "manager";

    public function beforeAction($action)
    {
        \Yii::$app->params["header"] = [
            "left" => [
                ['label' => 'Catalogue', 'url' => ['/yii/manager/catalogue']],
                ['label' => 'Article', 'url' => ['/yii/manager/article']],
            ],
            "right" => [
                ['label' => 'Logout', 'url' => ['/yii/manager/nav']],
            ]
        ];
        return parent::beforeAction($action); // TODO: Change the autogenerated stub
    }

    /**
     * Renders the index view for the module
     * @return string
     */
    public function actionIndex()
    {
        $this->redirect('manager/nav');
    }

    /**
     * Create the nav of header
     */
    public function actionNav()
    {

        $get = \Yii::$app->request->get();
        //get the nav data to fill the form
        if (isset($get["nav"])) {
            return $this->render('nav', [
                "nav" => FrameNavs::findOne(["id" => $get['nav']])
            ]);
        }

        //move the nav ahead
//        if (isset($get["move"]) && $get["move"] == "ahead"){
//            $aheadNav = FrameNavs::find()->where(["location" => "head"])->andWhere(["<", "id", $get["id"]])->orderBy("id desc")->one();
//            if($aheadNav) {
//                $current = FrameNavs::findOne(["id" => $get["id"]]);
//                $id = $aheadNav->id;
//                $aheadNav->id = 1000000;
//                $aheadNav->save();
//                $current->id = $id;
//                $current->save();
//                $aheadNav->id = $get["id"];
//                $aheadNav->save();
//                $this->render('nav', [
//                    "nav" => $current
//                ]);
//            }
//        }
        //move the nav behind
        if (isset($get["move"])) {
            $nextNav = FrameNavs::find()->where(["location" => "head"])->andWhere([$get["move"] == "ahead" ? "<" : ">", "id", $get["id"]])->orderBy(["id" => ($get["move"] == "ahead") ? SORT_DESC : SORT_ASC])->one();
            if ($nextNav) {
                $current = FrameNavs::findOne(["id" => $get["id"]]);
                $id = $nextNav->id;
                $nextNav->id = 1000000;
                $nextNav->save();
                $current->id = $id;
                $current->save();
                $nextNav->id = $get["id"];
                $nextNav->save();
                $this->redirect("nav?nav=" . $current->id);
            }
        }


        $params = \Yii::$app->request->post();
        $model = new FrameNavs();
        if ($model->load($params) && $model->validate()) {
            //save
            $model->save();
        }
        return $this->render('nav', [
            "nav" => $model
        ]);
    }

    public function actionCatalogue()
    {
        if(\Yii::$app->request->get("delete")){
            FrameCatalogue::deleteAll(["id" => \Yii::$app->request->get("delete")]);
        }
        $searchModel = new FrameCatalogue();
        $dataProvider = $searchModel->search(\Yii::$app->request->get());
        return $this->render('catalogue', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider
        ]);
    }

    public function actionRenderSaveDialog(){
        $params = \Yii::$app->request->post();
        if (isset($params["FrameCatalogue"])) {
            $post = \Yii::$app->request->post();
            $model = new FrameCatalogue();
            if ($model->load($post) && $model->validate()) {
                if (isset($post["FrameCatalogue"]["id"]) && $post["FrameCatalogue"]["id"] > 0){
                    $model = FrameCatalogue::findOne(["id" => $post["FrameCatalogue"]["id"]]);

                    $model->attributes = $post["FrameCatalogue"];
                    //var_dump($model->attributes);die;
                    //$model->save();
                }
                $model->save();
                $this->redirect('catalogue');
            } else {
                $result = $this->renderAjax("catalogue-save-dialog", [
                    'header' => ucfirst($params["type"]),
                    'model' => $model
                ]);
                $result = str_replace( '"show":false', '"show":true', $result);
                return $result;
            }
        }
        return $this->renderAjax("catalogue-save-dialog", [
            'header' => isset($params["type"]) ? ucfirst($params["type"]) : "Create",
            'model' => (isset($params["id"]) && $params["id"] > 0) ? FrameCatalogue::findOne(["id" => $params["id"]]) : (new FrameCatalogue())
        ]);
    }



    public function actionArticle()
    {
        //save node
        if (\Yii::$app->request->isPost && isset($_POST["FrameDir"])) {
            $model = new FrameDir();
            if ($model->load(\Yii::$app->request->post()) && $model->validate()){
                $model->save();
            }
        }
        return $this->render("article", [
            "sidebar" => new FrameDir(),
            "article" => new FrameArticles()
        ]);
    }


    public function actionAddNode(){
        $node = FrameDir::find()->orderBy("id desc")->limit(1)->one();
        $node->id += 1;
        $node->attributes = \Yii::$app->request->post();
        $node->save();
        return true;
    }

    public function actionRenameNode(){
        $node = FrameDir::findOne(["id" => \Yii::$app->request->post("id")]);
        $node->dname = \Yii::$app->request->post("dname");
        $node->save();
        return true;
    }

    public function actionRemoveNode(){
        FrameDir::deleteAll(["id" => \Yii::$app->request->post("id")]);
        return true;
    }

    public $enableCsrfValidation = false;
    public function actionUploadImage(){
        $filename = "upload/articles/images/" . uniqid() . "-" . $_FILES["editormd-image-file"]["name"];
        if(UploadedFile::getInstanceByName("editormd-image-file")->saveAs($filename)){
            return json_encode([
                "success" => 1,
                "message"  => "success",
                "url" => "/" . $filename
            ]);
        }
        return json_encode([
            "success" => 0,
            "message"  => "error",
            "url" => ""
        ]);
    }
}
